package com.matuw.android.util;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * @author Shihwan
 * @date 2024/2/5
 */
public class BroadcastUtils {

    /**
     * 取消广播注册
     */
    public static boolean unregister(Context context, BroadcastReceiver receiver) {
        if (context == null || receiver == null) {
            return false;
        }

        // 检查有没有注册过
        try {
            // 暂时没有好的办法，只有try了，后续有好的方案在替换
            context.unregisterReceiver(receiver);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    @IntDef(flag = true, value = {Context.RECEIVER_VISIBLE_TO_INSTANT_APPS, Context.RECEIVER_EXPORTED, Context.RECEIVER_NOT_EXPORTED,})
    @Retention(RetentionPolicy.SOURCE)
    public @interface RegisterReceiverFlags {
    }

    public static Intent register(@NonNull Context context, @NonNull BroadcastReceiver receiver, @NonNull IntentFilter filter) {
        return register(context, receiver, filter, false);
    }

    @SuppressLint("InlinedApi")
    public static Intent register(@NonNull Context context,
                                  @NonNull BroadcastReceiver receiver,
                                  @NonNull IntentFilter filter,
                                  boolean export) {

        return register(context, receiver, filter, null, null, export ? Context.RECEIVER_EXPORTED : Context.RECEIVER_NOT_EXPORTED);
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public static Intent register(@NonNull Context context,
                                  @NonNull BroadcastReceiver receiver,
                                  @NonNull IntentFilter filter,
                                  @Nullable String broadcastPermission,
                                  @Nullable Handler scheduler,
                                  @RegisterReceiverFlags int flags) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Use the new flag for API level 26 and above
            return context.registerReceiver(receiver, filter, broadcastPermission, scheduler, flags);
        }

        return context.registerReceiver(receiver, filter);
    }
}
